package com.biz.primus.ms.promotion.dao.redis;

import com.biz.primus.base.redis.CrudRedisDao;
import com.biz.primus.base.redis.bean.BaseRedisObject;
import com.biz.primus.base.redis.util.RedisUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.io.Serializable;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;

/**
 * 促销Redis Dao基类
 *
 * @author david-liu
 */
public abstract class BasePromotionRedisDao<T extends BaseRedisObject<ID>, ID extends Serializable> extends CrudRedisDao<T, ID> {

    /**
     * 批量获取秒杀活动商品信息
     *
     * @param promotionIds 秒杀活动ID集合
     * @return 商品集合
     */
    public Map<Long, List<Long>> getPromotionProducts(List<Long> promotionIds, Function<? super Long, ? extends String> mapper) {
        if (CollectionUtils.isEmpty(promotionIds)) {
            return Collections.emptyMap();
        }
        List<String> promotionProductSortedSetKeys = promotionIds.stream().map(mapper).collect(Collectors.toList());
        List<Object> objects = super.pipeZrange(promotionProductSortedSetKeys);
        Map<Long, List<Long>> ret = Maps.newLinkedHashMap();
        Iterator<Long> iterator = promotionIds.iterator();
        for (Object object : objects) {
            List<Long> productIds = Lists.newArrayListWithCapacity(objects.size());
            for (Object o : ((LinkedHashSet) object)) {
                Long val = RedisUtil.byteArrayToLong((byte[]) o);
                if (Objects.nonNull(val)) {
                    productIds.add(val);
                }
            }
            ret.put(iterator.next(), productIds);
        }
        return ret;

    }
}
